<template>
  <div class="exam-history-page">
    <div class="page-header">
      <h2>考试历史</h2>
      <p>查看您的所有考试记录和成绩</p>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <div class="filter-controls">
        <el-select v-model="filterParams.examType" placeholder="考试类型" clearable style="width: 150px;">
          <el-option label="全部" value="" />
          <el-option label="特定技能" value="特定技能" />
          <el-option label="JFT" value="JFT" />
          <el-option label="JLPT" value="JLPT" />
        </el-select>
        
        <el-select v-model="filterParams.result" placeholder="考试结果" clearable style="width: 150px;">
          <el-option label="全部" value="" />
          <el-option label="通过" value="通过" />
          <el-option label="未通过" value="未通过" />
        </el-select>
        
        <el-date-picker
          v-model="filterParams.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 250px;"
        />
        
        <el-input
          v-model="filterParams.keyword"
          placeholder="搜索考试名称"
          style="width: 200px;"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><Calendar /></el-icon>
          </div>
          <div class="stat-content">
            <h3>{{ stats.totalExams }}</h3>
            <p>总考试次数</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><Trophy /></el-icon>
          </div>
          <div class="stat-content">
            <h3>{{ stats.passedExams }}</h3>
            <p>通过考试</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-content">
            <h3>{{ stats.averageScore }}</h3>
            <p>平均分数</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <h3>{{ stats.totalStudyTime }}</h3>
            <p>总学习时长(小时)</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 考试记录列表 -->
    <div class="history-section">
      <div class="section-header">
        <h3>考试记录</h3>
        <!--<div class="export-actions">-->
          <!--<el-button type="success" size="small" @click="exportHistory">-->
            <!--导出记录-->
          <!--</el-button>-->
        <!--</div>-->
      </div>
      
      <div class="history-table">
        <el-table 
          :data="examHistory" 
          style="width: 100%"
          v-loading="loading"
          :empty-text="emptyText"
        >
          <el-table-column prop="examName" label="考试名称" min-width="200">
            <template #default="scope">
              <div class="exam-name">
                <img :src="scope.row.examIcon" :alt="scope.row.examName" class="exam-icon" />
                <div>
                  <div class="exam-title">{{ scope.row.examName }}</div>
                  <div class="exam-type">{{ scope.row.examType }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="startTime" label="考试时间" width="150">
            <template #default="scope">
              {{ formatDateTime(scope.row.startTime) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="duration" label="用时" width="100">
            <template #default="scope">
              {{ scope.row.duration }}分钟
            </template>
          </el-table-column>
          
          <el-table-column prop="score" label="成绩" width="100">
            <template #default="scope">
              <span v-if="scope.row.score" class="score" :class="getScoreClass(scope.row.score)">
                {{ scope.row.score }}分
              </span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="result" label="结果" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.result" :type="scope.row.result === '通过' ? 'success' : 'danger'">
                {{ scope.row.result }}
              </el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small"
                @click="viewResult(scope.row.id)"
              >
                查看详情
              </el-button>
              <el-button 
                type="warning" 
                size="small"
                @click="retakeExam(scope.row)"
                v-if="scope.row.result !== '通过'"
              >
                重新考试
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 成绩趋势图表 -->
    <!--<div class="chart-section">-->
      <!--<div class="section-header">-->
        <!--<h3>成绩趋势</h3>-->
        <!--<div class="chart-controls">-->
          <!--<el-select v-model="chartTimeRange" placeholder="时间范围" style="width: 120px;">-->
            <!--<el-option label="最近7天" value="7" />-->
            <!--<el-option label="最近30天" value="30" />-->
            <!--<el-option label="最近90天" value="90" />-->
            <!--<el-option label="全部" value="all" />-->
          <!--</el-select>-->
        <!--</div>-->
      <!--</div>-->
      <!---->
      <!--<div class="chart-container">-->
        <!--<div class="chart-placeholder">-->
          <!--<el-icon size="80" color="#409EFF"><TrendCharts /></el-icon>-->
          <!--<p>成绩趋势图表</p>-->
          <!--<p class="chart-note">显示您的考试成绩变化趋势，帮助分析学习效果</p>-->
        <!--</div>-->
      <!--</div>-->
    <!--</div>-->
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Search, 
  Calendar, 
  Trophy, 
  TrendCharts, 
  Clock 
} from '@element-plus/icons-vue'
import { getExamHistory, getExamStats } from '@/api/system'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const examHistory = ref([])
const stats = ref({
  totalExams: 0,
  passedExams: 0,
  averageScore: 0,
  totalStudyTime: 0
})

// 筛选参数
const filterParams = ref({
  examType: '',
  result: '',
  dateRange: [],
  keyword: ''
})

// 分页参数
const pagination = ref({
  pageNum: 1,
  pageSize: 20,
  total: 0
})

// 图表参数
const chartTimeRange = ref('30')

// 计算属性
const emptyText = computed(() => {
  if (loading.value) return '加载中...'
  if (filterParams.value.keyword || filterParams.value.examType || filterParams.value.result || filterParams.value.dateRange.length > 0) {
    return '没有找到符合条件的考试记录'
  }
  return '暂无考试记录'
})

// 获取考试历史
const fetchExamHistory = async () => {
  loading.value = true
  try {
    // 使用mock数据
    const mockExamHistory = [
      {
        id: 1,
        examId: 1,
        examName: '日语N5基础语法考试',
        examType: 'JLPT',
        examDate: '2024-01-15T10:00:00Z',
        score: 85,
        status: 'passed',
        duration: 45,
        totalQuestions: 50,
        correctAnswers: 42,
        wrongAnswers: 8,
        passScore: 60
      },
      {
        id: 2,
        examId: 2,
        examName: '商务日语会话考试',
        examType: '特定技能',
        examDate: '2024-01-10T14:00:00Z',
        score: 72,
        status: 'passed',
        duration: 78,
        totalQuestions: 60,
        correctAnswers: 43,
        wrongAnswers: 17,
        passScore: 70
      },
      {
        id: 3,
        examId: 3,
        examName: '日语听力理解考试',
        examType: 'JLPT',
        examDate: '2024-01-05T09:00:00Z',
        score: 68,
        status: 'failed',
        duration: 70,
        totalQuestions: 40,
        correctAnswers: 27,
        wrongAnswers: 13,
        passScore: 65
      },
      {
        id: 4,
        examId: 4,
        examName: 'JFT基础考试',
        examType: 'JFT',
        examDate: '2024-01-01T15:00:00Z',
        score: 88,
        status: 'passed',
        duration: 40,
        totalQuestions: 30,
        correctAnswers: 26,
        wrongAnswers: 4,
        passScore: 55
      },
      {
        id: 5,
        examId: 5,
        examName: '日语写作表达考试',
        examType: '特定技能',
        examDate: '2023-12-28T11:00:00Z',
        score: 76,
        status: 'passed',
        duration: 95,
        totalQuestions: 80,
        correctAnswers: 61,
        wrongAnswers: 19,
        passScore: 75
      },
      {
        id: 6,
        examId: 6,
        examName: '日语阅读理解考试',
        examType: 'JLPT',
        examDate: '2023-12-25T13:00:00Z',
        score: 82,
        status: 'passed',
        duration: 85,
        totalQuestions: 70,
        correctAnswers: 57,
        wrongAnswers: 13,
        passScore: 70
      }
    ]
    
    // 模拟筛选
    let filtered = mockExamHistory
    
    if (filterParams.value.examType) {
      filtered = filtered.filter(e => e.examType === filterParams.value.examType)
    }
    
    if (filterParams.value.result) {
      if (filterParams.value.result === 'passed') {
        filtered = filtered.filter(e => e.status === 'passed')
      } else if (filterParams.value.result === 'failed') {
        filtered = filtered.filter(e => e.status === 'failed')
      }
    }
    
    if (filterParams.value.keyword) {
      filtered = filtered.filter(e => 
        e.examName.toLowerCase().includes(filterParams.value.keyword.toLowerCase())
      )
    }
    
    // 模拟分页
    const start = (pagination.value.pageNum - 1) * pagination.value.pageSize
    const end = start + pagination.value.pageSize
    examHistory.value = filtered.slice(start, end)
    pagination.value.total = filtered.length
    
  } catch (error) {
    console.error('获取考试历史失败:', error)
    ElMessage.error('获取考试历史失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const fetchStats = async () => {
  try {
    // 使用mock数据
    stats.value = {
      totalExams: 15,
      passedExams: 12,
      averageScore: 78,
      totalStudyTime: 45
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.pageNum = 1
  fetchExamHistory()
}

// 重置筛选
const resetFilter = () => {
  filterParams.value = {
    examType: '',
    result: '',
    dateRange: [],
    keyword: ''
  }
  pagination.value.pageNum = 1
  fetchExamHistory()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.pageNum = 1
  fetchExamHistory()
}

const handleCurrentChange = (page) => {
  pagination.value.pageNum = page
  fetchExamHistory()
}

// 获取成绩样式类
const getScoreClass = (score) => {
  if (score >= 90) return 'excellent'
  if (score >= 80) return 'good'
  if (score >= 70) return 'pass'
  return 'fail'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN')
}

// 查看考试结果
const viewResult = (resultId) => {
  router.push({
    path: '/exam-result',
    query: { resultId }
  })
}

// 重新考试
const retakeExam = (exam) => {
  router.push({
    path: '/exam-detail',
    params: { id: exam.examId }
  })
}

// 导出记录
const exportHistory = () => {
  ElMessage.success('导出功能开发中')
}

// 监听图表时间范围变化
watch(chartTimeRange, (newValue) => {
  // 这里可以重新获取图表数据
  console.log('图表时间范围变化:', newValue)
})

onMounted(() => {
  fetchExamHistory()
  fetchStats()
})
</script>

<style scoped>
.exam-history-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px 0;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h2 {
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-size: 2rem;
}

.page-header p {
  color: #666;
  margin: 0;
  font-size: 1.1rem;
}

.filter-section {
  max-width: 1200px;
  margin: 0 auto 30px;
  padding: 0 20px;
}

.filter-controls {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.stats-section {
  max-width: 1200px;
  margin: 0 auto 30px;
  padding: 0 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  font-size: 2.5rem;
  color: #409EFF;
}

.stat-content h3 {
  margin: 0 0 5px 0;
  font-size: 2rem;
  color: #2c3e50;
}

.stat-content p {
  margin: 0;
  color: #666;
  font-size: 0.9rem;
}

.history-section {
  max-width: 1200px;
  margin: 0 auto 40px;
  padding: 0 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.section-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.5rem;
}

.history-table {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.exam-name {
  display: flex;
  align-items: center;
  gap: 12px;
}

.exam-icon {
  width: 40px;
  height: 40px;
  border-radius: 6px;
}

.exam-title {
  font-weight: 500;
  color: #2c3e50;
}

.exam-type {
  font-size: 0.8rem;
  color: #666;
  margin-top: 2px;
}

.score {
  font-weight: bold;
}

.score.excellent {
  color: #67C23A;
}

.score.good {
  color: #409EFF;
}

.score.pass {
  color: #E6A23C;
}

.score.fail {
  color: #F56C6C;
}

.pagination-wrapper {
  text-align: center;
  margin-top: 30px;
}

.chart-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.chart-container {
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.chart-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #666;
}

.chart-placeholder p {
  margin: 10px 0 0 0;
  font-size: 1rem;
}

.chart-note {
  font-size: 0.9rem;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .chart-container {
    padding: 20px;
  }
}
</style>
